package com.oliver.picturebackend.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.oliver.picturebackend.config.CosClientConfig;
import com.oliver.picturebackend.exception.BusinessException;
import com.oliver.picturebackend.exception.ErrorCode;
import com.oliver.picturebackend.exception.ThrowUtils;
import com.oliver.picturebackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @ClassName FileManager
 * @Description TODO
 * @Author snow
 * @Date 2024/12/13 21:26
 **/

/**
 * 文件服务已废弃,改为upload包的模板方法
 */
@Deprecated
@Service
@Slf4j
public class FileManager {

    @Autowired
    private CosManager cosManager;

    @Autowired
    private CosClientConfig cosClientConfig;

    public UploadPictureResult uploadPicture(MultipartFile multipartFile,String uploadPathPrefix){
        //  校验图片
        validPicture(multipartFile);
        //  图片上传路径
        String uuid = RandomUtil.randomString(16);
        String originFileName= multipartFile.getOriginalFilename();;
        //  日期_前缀.后缀
        String uploadFile = String.format("%s_%s.%s",new Date(),uploadPathPrefix, FileUtil.getSuffix(originFileName));
        File file = null;
        try{
            //  创建临时文件
            file = File.createTempFile(uploadFile,null);
            multipartFile.transferTo(file);
            //  图片上传
            PutObjectResult putObjectResult = cosManager.putObject(uploadFile, file);
            //  获取到图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //  封装返回类
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            double picScale = NumberUtil.round((width * 1.0 / height),2).doubleValue();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadFile);
            uploadPictureResult.setPicName(FileUtil.mainName(originFileName));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            return uploadPictureResult;
        }catch (Exception e){
            log.error("图片上传失败",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传文件失败");
        }finally {
            //  删除临时文件
            this.deleteTemplate(file);
        }
    }



    /**
     * 校验图片信息
     * @param multipartFile
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null,ErrorCode.PARAMS_ERROR);
        //  1.校验文件大小
        final long ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(multipartFile.getSize() > ONE_M * 2,ErrorCode.PARAMS_ERROR,"文件大小不能超过 2MB");
        //  2.校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> ALLOW_UPLOAD_SUFFIX = Arrays.asList("jpeg","jpg","png","webp");
        ThrowUtils.throwIf(!ALLOW_UPLOAD_SUFFIX.contains(fileSuffix),ErrorCode.SYSTEM_ERROR,"文件类型错误");
    }

    /**
     * 删除临时文件
     * @param file
     */
    private void deleteTemplate(File file) {
        if (file == null){
            return;
        }
        //  删除临时文件
        boolean delete = file.delete();
        if (!delete){
            log.error("file upload error, filePath = {}",file.getAbsolutePath());
        }
    }

}
